class Register {
  constructor () {
    this.bindEvent()
  }

  bindEvent () {
    $('.register-btn span').on('click', () => {
      this.register()
    })

    $('#username').on('blur', () => {
      this.validUsername()
    })
    $('#password').on('blur', () => {
      this.validPassword()
    })
  }

  validUsername () {
    let $item = $('#username').parents('.form-item')
    if ($('#username').val().length < 3 || $('#username').val().length > 8) {
      $item.find('.errorDiv').show()
      $('#username').parent().addClass('error')
      return false
    } else {
      $item.find('.errorDiv').hide()
      $('#username').parent().removeClass('error')
      return true
    }
  }

  validPassword () {
    let $item = $('#password').parents('.form-item')
    if ($('#password').val().length < 6 || $('#password').val().length > 12) {
      $item.find('.errorDiv').show()
      $('#password').parent().addClass('error')
      return false
    } else {
      $item.find('.errorDiv').hide()
      $('#password').parent().removeClass('error')
      return true
    }
  }

  register () {
    let username = $('#username').val()
    let password = $('#password').val()

    if (this.validPassword() && this.validUsername()) {
      let newUser = {
        username,
        password
      }

      let userInfo = localStorage.getItem('userInfo')

      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        let isExist =userInfo.some(item => {
          return item.username === username
        })

        if (isExist) {
          alert('用户名已存在')
          return false
        }

        userInfo.push(newUser)

        localStorage.setItem('userInfo', JSON.stringify(userInfo))

        $('.success').show()

        setTimeout(()=>{
          location.href = '/login.html'
        },1500)
      }else {
        localStorage.setItem('userInfo',JSON.stringify([newUser]))
        $('.success').show()

        setTimeout(()=>{
          location.href = '/login.html'
        },1500)
      }
    }
  }
}

new Register()
